#!-*- coding:utf-8 -*-

from django.http import Http404
from django.shortcuts import redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
from django.contrib.contenttypes.models import ContentType 

from ihlj import settings
from models import Image
import os, random
from hashlib import md5

@login_required
@require_POST
def upload(request):
    try:
        ctypeid = request.POST.get("ctypeid")
        objid = request.POST.get("objid")
    except ValueError:
        raise Http404("param type error")

    try:
        objtype = ContentType.objects.get_for_id(ctypeid)
    except ContentType.DoesNotExists:
        raise Http404("objtype not exists")

    obj = get_object_or_404(objtype.model_class(), pk=objid)

    redirect_to = request.POST.get("redirect_to", "")
    imgdesc = request.POST.get("imgdesc", "")
    imgtype = request.POST.get("imgtype", "")

    try:
        imgfile = request.FILES["image"]
    except KeyError:
        raise Http404("no image uploaded")

    ext = os.path.splitext(imgfile.name)[1]
    if ext not in (".jpg", ".png", ".gif", ".jpeg"):
        raise Http404("image type '%s' not supported"%(ext))
 
    hashobj = md5(request.user.username + imgfile.name + str(random.random()))
    hashkey = hashobj.hexdigest()
    relative_path = os.path.join(objtype.app_label, hashkey[0], hashkey[1], hashkey[2:]) + ext
    path = os.path.join(settings.MEDIA_ROOT, relative_path) 
    if not os.path.exists(os.path.dirname(path)):
        os.makedirs(os.path.dirname(path))

    fp = open(path, "ab")
    for trunk in imgfile.chunks(): 
        fp.write(trunk) 
    fp.close()

    imgobj = Image()
    imgobj.user = request.user 
    imgobj.content_type_id = ctypeid
    imgobj.object_id = objid 
    imgobj.path = relative_path 
    imgobj.size = imgfile.size
    imgobj.desc = request.POST.get("desc", "") 
    imgobj.ipaddr = request.META.get("REMOTE_ADDR", "")
    imgobj.save()
    
    return redirect(redirect_to)

